import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../providers/sudoku_provider.dart';
import '../model/difficulty.dart';

class GamePage extends StatefulWidget {
  final Difficulty difficulty;
  final int level;
  const GamePage({required this.difficulty, required this.level, Key? key})
    : super(key: key);

  @override
  State<GamePage> createState() => _GamePageState();
}

class _GamePageState extends State<GamePage> with WidgetsBindingObserver {
  late Stopwatch _stopwatch;
  bool _recorded = false;

  @override
  void initState() {
    super.initState();
    _stopwatch = Stopwatch()..start();
    // 注册生命周期观察者
    WidgetsBinding.instance.addObserver(this);
    // 使用 postFrameCallback 来避免在 build 过程中调用 setState
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<SudokuProvider>(
        context,
        listen: false,
      ).loadLevel(widget.difficulty, widget.level);
    });
  }

  @override
  void dispose() {
    // 注销生命周期观察者
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    final provider = Provider.of<SudokuProvider>(context, listen: false);

    switch (state) {
      case AppLifecycleState.paused:
      case AppLifecycleState.inactive:
      case AppLifecycleState.detached:
        // 应用进入后台或被暂停时，暂停计时器
        provider.pauseTimer();
        break;
      case AppLifecycleState.resumed:
        // 应用恢复到前台时，恢复计时器
        provider.resumeTimer();
        break;
      case AppLifecycleState.hidden:
        // 应用被隐藏时，暂停计时器
        provider.pauseTimer();
        break;
    }
  }

  @override
  void deactivate() {
    // 当页面失去焦点时暂停计时器
    final provider = Provider.of<SudokuProvider>(context, listen: false);
    provider.pauseTimer();
    super.deactivate();
  }

  @override
  void activate() {
    // 当页面重新获得焦点时恢复计时器
    super.activate();
    final provider = Provider.of<SudokuProvider>(context, listen: false);
    provider.resumeTimer();
  }

  Future<void> _setLevelPassed(int time) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(
      '${widget.difficulty.name}_${widget.level}_passed',
      true,
    );
    int? best = prefs.getInt(
      '${widget.difficulty.name}_${widget.level}_bestTime',
    );
    if (best == null || time < best) {
      await prefs.setInt(
        '${widget.difficulty.name}_${widget.level}_bestTime',
        time,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    return Scaffold(
      appBar: AppBar(
        title: Text('修炼手册'),
        actions: [
          IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {
              Navigator.of(context).popUntil((route) => route.isFirst);
            },
          ),
        ],
      ),
      extendBody: true, // 让body延伸到底部
      backgroundColor: Colors.transparent, // 设置透明背景
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Theme.of(context).scaffoldBackgroundColor,
              Theme.of(context).scaffoldBackgroundColor,
            ],
            stops: const [0.0, 0.8],
          ),
        ),
        child: SafeArea(
          bottom: false, // 不在底部应用SafeArea，实现沉浸式
          child: SingleChildScrollView(
            child: Consumer<SudokuProvider>(
              builder: (context, provider, child) {
                if (provider.gameCompleted && !_recorded) {
                  _stopwatch.stop();
                  _setLevelPassed(_stopwatch.elapsed.inSeconds);
                  _recorded = true;
                  Future.delayed(const Duration(milliseconds: 500), () {
                    if (mounted) {
                      showDialog(
                        context: context,
                        builder: (_) => AlertDialog(
                          title: const Text('通关成功！'),
                          content: Text('用时：${_stopwatch.elapsed.inSeconds}秒'),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.pop(context),
                              child: const Text('确定'),
                            ),
                          ],
                        ),
                      );
                    }
                  });
                }
                return Column(
                  children: [
                    Container(
                      margin: const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 0),
                      padding: const EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: isDark
                            ? const Color(0xFF2D3748)
                            : const Color(0xFFF7FAFC),
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: isDark
                                ? const Color(0x20000000)
                                : const Color(0x10000000),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.trending_up,
                                    size: 18,
                                    color: isDark
                                        ? const Color(0xFFE2E8F0)
                                        : const Color(0xFF2D3748),
                                  ),
                                  const SizedBox(width: 6),
                                  Text(
                                    '${provider.difficultyText} - 第${widget.level}关',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: isDark
                                          ? const Color(0xFFE2E8F0)
                                          : const Color(0xFF2D3748),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.lightbulb_outline,
                                    size: 16,
                                    color: isDark
                                        ? const Color(0xFFA0AEC0)
                                        : const Color(0xFF4A5568),
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    '${provider.hintsUsed}',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: isDark
                                          ? const Color(0xFFA0AEC0)
                                          : const Color(0xFF4A5568),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    provider.mistakes > 0
                                        ? Icons.error_outline
                                        : Icons.check_circle_outline,
                                    size: 18,
                                    color: provider.mistakes > 0
                                        ? (isDark
                                              ? const Color(0xFFFC8181)
                                              : const Color(0xFFE53E3E))
                                        : (isDark
                                              ? const Color(0xFF68D391)
                                              : const Color(0xFF38A169)),
                                  ),
                                  const SizedBox(width: 6),
                                  Text(
                                    '${provider.mistakes}',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: provider.mistakes > 0
                                          ? (isDark
                                                ? const Color(0xFFFC8181)
                                                : const Color(0xFFE53E3E))
                                          : (isDark
                                                ? const Color(0xFFE2E8F0)
                                                : const Color(0xFF2D3748)),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.timer_outlined,
                                    size: 16,
                                    color: isDark
                                        ? const Color(0xFF68D391)
                                        : const Color(0xFF38A169),
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    provider.getFormattedTime(),
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                      color: isDark
                                          ? const Color(0xFF68D391)
                                          : const Color(0xFF38A169),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    AspectRatio(
                      aspectRatio: 1.0,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: GridView.builder(
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 9,
                              ),
                          itemCount: 81,
                          physics: const NeverScrollableScrollPhysics(),
                          itemBuilder: (context, index) {
                            int row = index ~/ 9;
                            int col = index % 9;
                            bool isSelected =
                                row == provider.selectedRow &&
                                col == provider.selectedCol;
                            bool isEditable = provider.isEditable[row][col];
                            bool isError = provider.isError[row][col];
                            bool isCompleted = provider.gameCompleted;

                            Color backgroundColor;
                            if (isSelected) {
                              backgroundColor = isDark
                                  ? const Color(0xB34A90E2) // 70% opacity
                                  : const Color(0x804A90E2); // 50% opacity
                            } else if (isError) {
                              backgroundColor = isDark
                                  ? const Color(0xB3FF5252) // 70% opacity
                                  : const Color(0x80FF5252); // 50% opacity
                            } else {
                              bool shouldHighlight = false;
                              if (provider.selectedNumber != -1) {
                                int cellValue = -1;
                                if (provider.puzzle[row][col] != 0) {
                                  cellValue = provider.puzzle[row][col];
                                } else if (provider
                                        .userInput[row][col]
                                        .length ==
                                    1) {
                                  cellValue =
                                      provider.userInput[row][col].first;
                                }
                                shouldHighlight =
                                    cellValue == provider.selectedNumber;
                              }

                              if (isCompleted) {
                                backgroundColor = isDark
                                    ? const Color(
                                        0x804CAF50,
                                      ) // Green with 50% opacity
                                    : const Color(
                                        0x4D4CAF50,
                                      ); // Green with 30% opacity
                              } else if (shouldHighlight) {
                                backgroundColor = isDark
                                    ? const Color(
                                        0x66FFC107,
                                      ) // Amber with 40% opacity
                                    : const Color(
                                        0x66FFE082,
                                      ); // Light amber with 40% opacity
                              } else if ((row + col) % 2 == 0) {
                                backgroundColor = isDark
                                    ? const Color(
                                        0x33FFFFFF,
                                      ) // White with 20% opacity
                                    : const Color(
                                        0x1A000000,
                                      ); // Black with 10% opacity
                              } else {
                                backgroundColor = isDark
                                    ? const Color(0xFF2D3748) // Dark blue-gray
                                    : const Color(
                                        0xFFFAFAFA,
                                      ); // Very light gray
                              }
                            }

                            Color numberColor = isEditable
                                ? (isDark
                                      ? const Color(
                                          0xFFE2E8F0,
                                        ) // Light gray for dark mode
                                      : const Color(
                                          0xFF1A202C,
                                        )) // Dark gray for light mode
                                : (isDark
                                      ? const Color(
                                          0xFF90CDF4,
                                        ) // Light blue for dark mode
                                      : const Color(
                                          0xFF2D3748,
                                        )); // Dark blue-gray for light mode

                            return GestureDetector(
                              onTap: () => provider.selectCell(row, col),
                              child: Container(
                                decoration: BoxDecoration(
                                  border: Border(
                                    top: BorderSide(
                                      width: row == 0
                                          ? 3.0
                                          : (row % 3 == 0 ? 2.0 : 0.8),
                                      color: isDark
                                          ? const Color(
                                              0xFF4A5568,
                                            ) // Medium gray for dark mode
                                          : const Color(
                                              0xFF2D3748,
                                            ), // Dark gray for light mode
                                    ),
                                    left: BorderSide(
                                      width: col == 0
                                          ? 3.0
                                          : (col % 3 == 0 ? 2.0 : 0.8),
                                      color: isDark
                                          ? const Color(0xFF4A5568)
                                          : const Color(0xFF2D3748),
                                    ),
                                    right: BorderSide(
                                      width: col == 8 ? 3.0 : 0.8,
                                      color: isDark
                                          ? const Color(0xFF4A5568)
                                          : const Color(0xFF2D3748),
                                    ),
                                    bottom: BorderSide(
                                      width: row == 8 ? 3.0 : 0.8,
                                      color: isDark
                                          ? const Color(0xFF4A5568)
                                          : const Color(0xFF2D3748),
                                    ),
                                  ),
                                  color: backgroundColor,
                                  boxShadow: isSelected
                                      ? [
                                          BoxShadow(
                                            color: isDark
                                                ? const Color(0x404A90E2)
                                                : const Color(0x304A90E2),
                                            blurRadius: 8,
                                            spreadRadius: 1,
                                          ),
                                        ]
                                      : null,
                                ),
                                child: Transform.scale(
                                  scale: isSelected ? 1.05 : 1.0,
                                  child: Center(
                                    child: provider.puzzle[row][col] != 0
                                        ? Text(
                                            '${provider.puzzle[row][col]}',
                                            style: TextStyle(
                                              fontSize: 20,
                                              fontWeight: FontWeight.bold,
                                              color: numberColor,
                                            ),
                                          )
                                        : provider
                                              .userInput[row][col]
                                              .isNotEmpty
                                        ? provider.userInput[row][col].length ==
                                                  1
                                              ? Text(
                                                  '${provider.userInput[row][col].first}',
                                                  style: TextStyle(
                                                    fontSize: 20,
                                                    color: numberColor,
                                                  ),
                                                )
                                              : GridView.count(
                                                  shrinkWrap: true,
                                                  physics:
                                                      const NeverScrollableScrollPhysics(),
                                                  crossAxisCount: 3,
                                                  childAspectRatio: 1.1,
                                                  mainAxisSpacing: 1,
                                                  crossAxisSpacing: 1,
                                                  padding: EdgeInsets.all(2),
                                                  children: List.generate(9, (
                                                    index,
                                                  ) {
                                                    final number = index + 1;
                                                    return provider
                                                            .userInput[row][col]
                                                            .contains(number)
                                                        ? Center(
                                                            child: Text(
                                                              '$number',
                                                              style: TextStyle(
                                                                fontSize: 8,
                                                                color:
                                                                    numberColor,
                                                              ),
                                                            ),
                                                          )
                                                        : Container();
                                                  }),
                                                )
                                        : SizedBox.shrink(),
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        left: 16.0,
                        right: 16.0,
                        bottom:
                            MediaQuery.of(context).padding.bottom +
                            16, // 为小白条留出空间
                      ),
                      padding: const EdgeInsets.all(20.0),
                      decoration: BoxDecoration(
                        color: isDark
                            ? const Color(0xFF2D3748)
                            : const Color(0xFFF7FAFC),
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color: isDark
                                ? const Color(0x20000000)
                                : const Color(0x10000000),
                            blurRadius: 12,
                            offset: const Offset(0, 4),
                          ),
                        ],
                      ),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              _buildActionButton(
                                context,
                                '提示',
                                Icons.lightbulb_outline,
                                provider.gameCompleted
                                    ? null
                                    : provider.useHint,
                                isDark,
                                const Color(0xFFFFC107),
                              ),
                              _buildActionButton(
                                context,
                                '清除',
                                Icons.clear,
                                provider.gameCompleted
                                    ? null
                                    : provider.clearSelectedCell,
                                isDark,
                                const Color(0xFFFF5722),
                              ),
                              _buildActionButton(
                                context,
                                '检查',
                                Icons.check_circle_outline,
                                provider.gameCompleted
                                    ? null
                                    : provider.checkSolution,
                                isDark,
                                const Color(0xFF4CAF50),
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),
                          GridView.count(
                            crossAxisCount: 5,
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            childAspectRatio: 1.0,
                            mainAxisSpacing: 8,
                            crossAxisSpacing: 8,
                            padding: const EdgeInsets.symmetric(horizontal: 8),
                            children: List.generate(9, (index) {
                              int number = index + 1;
                              bool canInput =
                                  !provider.gameCompleted &&
                                  provider.selectedRow != -1 &&
                                  provider.selectedCol != -1 &&
                                  provider.isEditable[provider
                                      .selectedRow][provider.selectedCol];
                              return Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  boxShadow: canInput
                                      ? [
                                          BoxShadow(
                                            color: isDark
                                                ? const Color(0x20000000)
                                                : const Color(0x15000000),
                                            blurRadius: 4,
                                            offset: const Offset(0, 2),
                                          ),
                                        ]
                                      : null,
                                ),
                                child: ElevatedButton(
                                  onPressed: canInput
                                      ? () => provider.enterNumber(number)
                                      : null,
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: canInput
                                        ? (isDark
                                              ? const Color(0xFF4A90E2)
                                              : const Color(0xFF3182CE))
                                        : (isDark
                                              ? const Color(0xFF2D3748)
                                              : const Color(0xFFE2E8F0)),
                                    foregroundColor: canInput
                                        ? Colors.white
                                        : (isDark
                                              ? const Color(0xFF4A5568)
                                              : const Color(0xFFA0AEC0)),
                                    elevation: canInput ? 2 : 0,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    padding: EdgeInsets.zero,
                                  ),
                                  child: Text(
                                    '$number',
                                    style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              );
                            }),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildActionButton(
    BuildContext context,
    String text,
    IconData icon,
    VoidCallback? onPressed,
    bool isDark,
    Color accentColor,
  ) {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 4.0),
        child: ElevatedButton.icon(
          onPressed: onPressed,
          icon: Icon(
            icon,
            size: 18,
            color: onPressed != null
                ? (isDark ? const Color(0xFF1A202C) : Colors.white)
                : (isDark ? const Color(0xFF4A5568) : const Color(0xFFA0AEC0)),
          ),
          label: Text(
            text,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: onPressed != null
                  ? (isDark ? const Color(0xFF1A202C) : Colors.white)
                  : (isDark
                        ? const Color(0xFF4A5568)
                        : const Color(0xFFA0AEC0)),
            ),
          ),
          style: ElevatedButton.styleFrom(
            backgroundColor: onPressed != null
                ? accentColor
                : (isDark ? const Color(0xFF2D3748) : const Color(0xFFE2E8F0)),
            foregroundColor: onPressed != null
                ? (isDark ? const Color(0xFF1A202C) : Colors.white)
                : (isDark ? const Color(0xFF4A5568) : const Color(0xFFA0AEC0)),
            elevation: onPressed != null ? 4 : 0,
            shadowColor: onPressed != null
                ? const Color(0x4D000000) // 30% black shadow
                : Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
          ),
        ),
      ),
    );
  }
}
